package logic

import (
	"api/pkg"
	"context"
	"net/http"
	"path"
	"time"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ImagesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewImagesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ImagesLogic {
	return &ImagesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ImagesLogic) Images(r *http.Request) (resp *types.Response, err error) {
	file, header, err := r.FormFile("images")
	if err != nil {
		return &types.Response{
			Code: 500,
			Msg:  "图片获取失败",
			Data: nil,
		}, nil
	}
	if header.Size > 1024*1024*200 {
		return &types.Response{
			Code: 500,
			Msg:  "图片过大",
			Data: nil,
		}, nil
	}
	ext := path.Ext(header.Filename)
	if ext != ".jpg" && ext != ".png" && ext != ".jpeg" {
		return &types.Response{
			Code: 500,
			Msg:  "图片格式错误",
			Data: nil,
		}, nil
	}
	filename := time.Now().Format("20241226194544") + ext

	pkg.QiNiu(file, header, filename)

	return &types.Response{
		Code: 200,
		Msg:  "上传成功",
		Data: nil,
	}, nil
}
